package com.example.controller;

import com.example.service.AuthService;
import com.example.util.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public Object doLogin(String username,
                          String password) {
        return authService.doLogin(username, password);
    }

    /* 这个接口是给Shiro判断用户没登录之后重定向使用 */
    @RequestMapping("/no_login")
    public Object noLogin() {
        return ResultUtil.unAuthenticated(); // 401的状态码
    }

    @GetMapping("/loginInfo")
    public Object loginInfo() {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> data = new HashMap<>();
        Object principal = subject.getPrincipal(); // 当前登录账号
        data.put("username", principal);
        Session session = subject.getSession();
        data.put("登录时间", session.getStartTimestamp());
        data.put("超时时间", session.getTimeout());
        return ResultUtil.success("账号已登录", data);
    }

    @GetMapping("/logout")
    public Object logout() {
        SecurityUtils.getSubject().logout();
        return ResultUtil.success("退出登录成功", null);
    }
}
